import { bindable, containerless } from 'aurelia-framework';

@containerless
export class EmEditableCalendar {

    @bindable value;
    @bindable placeholder;
    // @bindable startCalendar;
    // @bindable endCalendar;
    @bindable onchange;

    editing = false;

    // valueChanged(newValue, oldValue) {
    //     if (newValue) {
    //         $(this.calendarRef).calendar('set date', new Date(this.value));
    //     } else {
    //         $(this.calendarRef).calendar('clear');
    //     }
    // }

    /**
     * 当视图被附加到DOM中时被调用
     */
    attached() {
        this.blurHandler = () => {
            this.cancelHandler();
        };
        $(this.inputRef).on('blur', this.blurHandler);
    }

    _initCalendar() {
        $(this.calendarRef).calendar({
            today: true,
            type: 'date',
            // initialDate: this.value ? new Date(this.value) : null,
            // startCalendar: $(this.startCalendar)
            // endCalendar: $(this.endCalendar)
            onChange: (date, text, mode) => {
                this.value = date ? date.getTime() : null;
                this.cancelHandler();
                this.onchange && this.onchange(date);
            },
        }).calendar('set date', this.value ? new Date(this.value) : null, true, false);
    }

    cancelHandler() {
        this.editing = false;
    }

    editHandler() {
        this.editing = true;
        _.defer(() => {
            this._initCalendar();
            $(this.inputRef).select();
        });
    }
}
